//点击返回首页
function toIndex() {
    $('.cart').on('click', function () {
        location.href = './index.html'
    })
}


toIndex()
//获取用户的本地存储名称作为购物车名称
let userString = localStorage.getItem('USER')
let userList = JSON.parse(userString)
let nameC = userList.username

let cartStr = localStorage.getItem(`${nameC}`)
let cartList = JSON.parse(cartStr) || []

let allState = false

//进入页面就取出来渲染
function showCart() {
    if (cartList.length < 1) {
        $('#main').html('购物车还没有商品哦~')
    } else {
        let topStr = `<table>
    <tr>
        <td><input type='checkbox' name="allCheck" ${allState? 'checked':''}>全选</td>
        <td>商品图片</td>
        <td>商品名称</td>
        <td>商品价格</td>
        <td>
            更改数量
        </td>
        <td class="price">总金额</td>
        <td>
            操作
        </td>
    </tr>`
        let centerStr = cartList.map(item => {
            return `
        <tr>
        <td><input type='checkbox' name='singleCheck' ${item.state==true? 'checked':''} class="single" data-index="${item.id}"></td>
        <td><a href="../pages/details.html?id=${item.id}"><img src="${item.url}" alt=""></a></td>
        <td>${item.name}</td>
        <td class="gray">￥${item.price}</td>
        <td class="operate">
            <input type="button" value="-" name="minus" data-index="${item.id}" ${item.num <= 1 ? 'disabled' : ''} >
            <input type="text" value="${item.num}" name="inputCount" data-index="${item.id}">
            <input type="button" data-index="${item.id}" value="+" name="plus" data-index="${item.id}">
        </td>

        <td class="gray totalPrice">￥${item.singlePrice}</td>
        <td>
            <a href="#" class="addCollection" data-index="${item.id}">移入收藏夹</a>
            <span class="delete" data-index="${item.id}">删除</span>
        </td>
    </tr>
    `
        }).join('')

        let allStr = topStr + centerStr + `</table><div class="total fr">商品总价：<span>￥${ allPrice()}</span></div>`
        $('#main').html(allStr)
    }

}

showCart()
//点击加入收藏夹
function addCollection() {
    $('.addCollection').on('click', function (e) {
        e = e || window.event
        let target = $(e.target)
        e.preventDefault()
        //新增的收藏夹数组
        let listStr = localStorage.getItem(`Collection+${nameC}`)
        let list = JSON.parse(listStr) || []

        let id = target.attr('data-index')
        //当前点击商品的Id
        console.log('list >> ', list);
        let product = list.find(function (item) {
            return item.id == id
        }) //看看收藏夹里面有没有这个商品id  如果没有 prosuct就不存在
        if (product) {
            alert('这个宝贝已经在收藏夹里了哦~')
        } else {
            let index = cartList.findIndex(function (item) {
                return item.id == id
            })
            product = cartList[index]
            list.push(product) //移入新数组
            cartList.splice(index, 1) //删除原数组
            alert('移入成功')
            transformStr()
            showCart()
            localStorage.setItem(`Collection+${nameC}`, JSON.stringify(list))
        }
    })
}


//购物车计算等操作
function myCart() {
    $('#main').on('click', 'input[value="+"]', function () {
        let id = $(this).attr('data-index')
        addOrMinus(id, '+')
    })

    // 点击减一操作 获取当前点击的元素的id 查找list里面id相等的元素 让他的num--
    $('#main').on('click', 'input[value="-"]', function () {
        let id = $(this).attr('data-index')
        addOrMinus(id, '-')
    })

    //输入改变数量
    $('#main').on('change', 'input[name="inputCount"]', function (e) {
        let target = $(e.target) || $(e.srcElement)
        let id = target.attr('data-index')
        let product = cartList.find(item => item.id == id) //找到id对应的商品
        if (target.val() >= 1) {
            product.num = target.val()
        } else {
            product.num = 1 //先做判断再取值
        }
        product.singlePrice = (product.price * product.num).toFixed(2)


        transformStr()
        showCart()



    })

    //删除操作
    $('#main').on('click', '.delete', function () {
        // e = e || window.event
        // let target = e.target || e.srcElement
        let id = $(this).attr('data-index')
        let index = cartList.findIndex(function (item) {
            return item.id == id
        })
        cartList.splice(index, 1)

        showCart()
        transformStr()

    })

}

//单选和全选状态的操作
function checkedItem() {
    //如果点击的是全选框 遍历prosuctlist 把所有商品的状态取反
    //设置所有商品state状态为与全选框相同状态
    $('#main').on('click', 'input[name="allCheck"]', function () {
        allState = !allState
        // //遍历设置所有商品state状态为与全选框相同状态
        cartList.forEach(item => item.state = allState)
        // //并且让所有单选框状态为选中状态  在渲染中更改
        transformStr()
        showCart() //重新渲染页面

    })
    // 如果点击的是单选框 按照id查找到对应商品数组元素把状态取反   
    $('#main').on('click', 'input[name="singleCheck"]', function (e) {
        let target = $(e.target)
        let id = target.attr('data-index')
        let product = cartList.find(item => item.id == id) //找到id对应的商品
        //对当前状态进行取反
        product.state = !product.state
        // 判断是不是所有的状态都为true  有一个不为true  全选框就不选中 否则选中 更改全选框的状态
        allState = cartList.every(item => item.state == true)
        showCart() //重新渲染页面
        transformStr()

    })

}

//计算总金额
function allPrice() {
    let redTotal = $('.total>span')
    redTotal = redTotal[0]
    let sumPrice = cartList.reduce((sum, item) => sum + (item.state ? Number(item.singlePrice) : 0), 0)
    return sumPrice.toFixed(2)
    // redTotal.innerHTML = `￥${sumPrice.toFixed(2)}`
}

//加减操作的简化
function addOrMinus(id, operate) {
    let product = cartList.find(function (item) {
        return item.id == id
    })
    operate == '+' ? product.num++ : product.num--
    product.singlePrice = (product.price * product.num).toFixed(2)
    transformStr()
    showCart()
}
//存回
function transformStr() {
    localStorage.setItem(`${nameC}`, JSON.stringify(cartList))
}

//点击跳转收藏夹
function toCollection() {
    $('#toCollection').on('click', function () {
        location.href = '../pages/myFavorite.html'
    })
}


myCart()
checkedItem()
toCollection()
addCollection()